package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiDuAddressProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduAddressUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sky.utils.WeChatPayUtil;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private BaiduAddressUtil baiduAddressUtil;

    @Autowired
    private BaiDuAddressProperties baiDuAddressProperties;

    @Autowired
    private WebSocketServer webSocketServer;



    /**
     * 用户下单
     * 1.判断地址是否合法(是否为空，是否在范围之内...)，如果不合法,抛出异常，中断业务
     * 2.判断当前用户购物车数据是否存在，如果不存在，抛出异常，中断业务
     * 3.构建订单数据,填充几余字段信息等,插入表中
     * 4。构建订单详细数据
     * 5.清空当前用户的购物车数据
     * 6.构建V0返回数据
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submintOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.判断地址合法性（是否为空、是否再范围之内、）如果不合法，就抛出异常，中断业务
        //1.1调用地址薄的mapper层的根据id查询数据的方法，拿到地址数据
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        //1.2判断地址是否为空，如果为空就抛异常
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //TODO：判断是否在范围内明天做（用百度地图）
        log.info("商家地址:{}",baiDuAddressProperties.getAddress());

        //获取客户详细地址
        String provinceName = addressBook.getProvinceName();
        String cityName = addressBook.getCityName();
        String districtName = addressBook.getDistrictName();
        String detailAddress = addressBook.getDetail();
        String clientDetailAddress = provinceName + cityName + districtName + detailAddress;
        //调用百度地图地理编码服务接口,根据地址获取坐标(经度 \ 维度)
        String client = BaiduAddressUtil.getCoordinate(clientDetailAddress);
        System.out.println("client = " + client);
        String shop = BaiduAddressUtil.getCoordinate(baiDuAddressProperties.getAddress());
        System.out.println("shop = " + shop);
        //判断距离
        Double distance = BaiduAddressUtil.getDistance(shop, client);
        log.info("配送距离:{}",distance);
        System.out.println("------------------------------------");
        System.out.println("distance = " + distance);
        System.out.println("------------------------------------");

        //骑行的距离,太远的话就会无法测量,就会空指针异常

        //注意一定要先判断distance为null,才可以判断距离
        if (distance == null || distance > 50000.0){
            throw new AddressBookBusinessException(MessageConstant.OUT_OF_DISTANCE);
        }


        //2.判断当前用户购物车数据是否存在，如果不存在，抛出异常中断业务
        //2.1创建购车对象使用构造器拿到用户的userid
        ShoppingCart shoppingCart = ShoppingCart
                .builder()
                .userId(BaseContext.getCurrentId())
                .build();
        //2.2调用购物车的mapper层查数据的方法
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        //2.3判断当前用户下的购物车里是否有数据，如果没有抛异常
        //3.构建订单数据，填充冗余字段信息等，插入表中
        //3.1创建Orders对象
        Orders orders = new Orders();
        //3.2把DTO的数据拷贝到Entity中
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //3.3补充字段：
        //number
        orders.setNumber(System.currentTimeMillis() + "");
        //status
        orders.setStatus(Orders.PENDING_PAYMENT);
        //user-id
        orders.setUserId(BaseContext.getCurrentId());
        //order-time 订单时间
        orders.setOrderTime(LocalDateTime.now());
        //pay-status
        orders.setPayStatus(Orders.UN_PAID);
        //phone
        orders.setPhone(addressBook.getPhone());
        //address
        orders.setAddress(addressBook.getDetail());
        //user—name  //下单人
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        //consignee
        orders.setConsignee(addressBook.getConsignee());
        //插入数据
        ordersMapper.insert(orders); //TODO 数据回显
        log.info("订单数据插入表中完毕: {}", orders);

        //4.构建订单详细数据
        //4.1将购物车数据转换为订单详细数据
        ArrayList<OrderDetail> orderDetailArrayList = new ArrayList<>();
        //遍历数据（将购物车里面的数据拷贝到订单里面，然后填充字段,最后添加到集合中）
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            //填充字段
            orderDetail.setOrderId(orders.getId());
            //添加到集合中
            orderDetailArrayList.add(orderDetail);
        }
        //插入到订单信息表中
        orderDetailMapper.insertBatch(orderDetailArrayList);

        //5.清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        //6.构建VO返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO
                .builder()
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .id(orders.getId())
                .build();

        //通过WebSocket实现管理端页面和服务端保持长连接状态
        //来单提醒
        //创建一个map集合
        Map map = new HashMap();
        //约定服务端发送给客户端浏览器的数据格式为JSON，
        // 字段包括：type，orderId，content
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","来订单啦快来查看"+orders.getNumber());
        String josnStr = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(josnStr);

        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getUserById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);



    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO 订单分页查询封装类
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO, Integer flag) {

        //进行用户端还是管理端得判断
        if (flag == 1) {
            //用户端
            //获取当前用户的id,并赋值给ordersPageQueryDTO
            ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        }
        //设置分页查询参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //调mapper层分页查询方法直接返回page类型
        Page<Orders> page = ordersMapper.selectPage(ordersPageQueryDTO);

        //取出当前页的集合
        List<Orders> ordersList = page.getResult();

        //创建一个参数为vo类型的集合,用于接收数据
        List<OrderVO> orderVOList = new ArrayList<>();
        //遍历当前数据
        for (Orders orders : ordersList) {
            //创建一个vo类型的对象,用于接收每一次遍历的数据
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            //调mapper层方法,
            List<OrderDetail> orderDetailList = orderDetailMapper.selectById(orders.getId());
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }
        return new PageResult(page.getTotal(), orderVOList);
    }


    /**
     * 根据id查询订单详情
     *
     * @param id 参数
     * @return
     */
    @Override
    public OrderVO selectById(Long id) {
        //根据id查询订单表信息
        Orders orders = ordersMapper.selectOrderById(id);
        //把entrty数据拷贝到vo中
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        //获取到订单详情得信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectById(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }


    //根据id修改订单状态
    @Override
    public void updateById(Long id) {
        ordersMapper.updateById(id);
    }

    //再来一单
    @Override
    public void InsertById(Long id) {
        //根据订单id查询到订单的数据

        //从数据库中获得的是一个集合
        //因为一个订单有很多个菜品
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);

        //要将每一个菜品都添加到购物车中
        //所以要遍历获取到的多个菜品集合
        for (OrderDetail orderDetail : orderDetails) {
            //orderDetail为一个菜品,需要将这个菜品存入到购物车中
            //所以,创建一个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();

            //1.先将菜品的信息复制到购物车中
            BeanUtils.copyProperties(orderDetail, shoppingCart);

            //2.填充其余的字段
            //设置当前用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());

            //设置创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());

            //将这一个菜品添加都购物车中
            shoppingCartMapper.insert(shoppingCart);
        }
    }


    /**
     * 根据订单状态查询订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO statisticsOrders() {

        //返回OrderStatisticsVO对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        //该对象中有三个属性需要赋值

        //获取该对象得三个属性
        //获取待派送数量
        Integer one = ordersMapper.countConfirmed();
        //赋值给orderStatisticsVO对象
        orderStatisticsVO.setConfirmed(one);
            //获取派送中得数量
       Integer two = ordersMapper.countDeliveryInProgress();
       orderStatisticsVO.setDeliveryInProgress(two);

            //获取待接单数量
       Integer three = ordersMapper.countToBeConfirmed();
                orderStatisticsVO.setToBeConfirmed(three);
        return orderStatisticsVO;
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //1.首先要根据订单id查询订单
        Orders order = ordersMapper.selectOrderById(ordersRejectionDTO.getId());

        //2.判断订单状态 status -> 2
        Integer orderStatus = order.getStatus();

        //如果订单状态为待接单才可以进行拒单
        if (orderStatus == 2) {
            //修改订单状态为已取消 -> 6
            order.setStatus(Orders.CANCELLED);

            //修改支付状态为退款
            order.setPayStatus(Orders.REFUND);

            //设置订单取消时间
            order.setCancelTime(LocalDateTime.now());

            //设置拒绝的原因
            order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        }

        //更新数据库
        ordersMapper.update(order);
    }


    /**
     *  接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //1.首先根据订单id查询到订单数据
        Orders order = ordersMapper.selectOrderById(ordersConfirmDTO.getId());

        //判断订单状态为2才可以进行接单
        Integer orderStatus = order.getStatus();
        if (orderStatus==2){
            //修改订单状态为3
            order.setStatus(Orders.CONFIRMED);
        }

        //3.更新数据库
        ordersMapper.update(order);
    }


    /**
     *  取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //1.先根据订单id查询订单
        Orders order = ordersMapper.selectOrderById(ordersCancelDTO.getId());

        //2.判断订单状态修改字段
        Integer orderStatus = order.getStatus();
        if (orderStatus==1 || orderStatus==3 || orderStatus==4 || orderStatus==5){
            //修改订单状态为已取消->6
            order.setStatus(Orders.CANCELLED);

            //修改订单取消时间
            order.setCancelTime(LocalDateTime.now());

            //修改订单取消原因
            order.setCancelReason(ordersCancelDTO.getCancelReason());

            //如果是已付款状态修改支付状态为退款
            if (order.getPayStatus()==1){
                order.setPayStatus(Orders.REFUND);
            }
        }
        //3.更新数据库
        ordersMapper.update(order);
    }


    /**
     *  派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        //1.查询订单信息
        Orders order = ordersMapper.selectOrderById(id);

        //2.修改订单字段
        Integer orderStatus = order.getStatus();
        if (orderStatus==3){
            //修改订单状态为派送中->4
            order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        }
        //3.更新数据库
        ordersMapper.update(order);
    }


    /**
     *  完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        //1.根据id查询订单信息
        Orders order = ordersMapper.selectOrderById(id);
        //2.修改订单字段
        Integer orderStatus = order.getStatus();
        if (orderStatus==4){
            //修改订单状态为已完成->5
            order.setStatus(Orders.COMPLETED);
        }
        //3.更新数据库
        ordersMapper.update(order);
    }


    /**
     *  催单
     * @param orderid 订单id
     */
    @Override
    public void reminder(Long orderid) {
            //根据订单id查询订单
        Orders order = ordersMapper.selectOrderById(orderid);

        //判断订单是否存在
        if (order==null){
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //创建一个map集合
        Map map = new HashMap();
        //添加数据
        map.put("type",2);
        map.put("orderId",orderid);
        map.put("content","用户"+order.getNumber()+"来催单啦！");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
